package istar.behaviour;

import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;
import istar.agent.IstarJadeAgent;
import istar.impl.AbstractMainGoal;

public class IstarMainBehaviour extends IstarBehaviour{
	
	
	public IstarMainBehaviour(AbstractMainGoal _mainGoal){
		super(_mainGoal);
	}
	

	@Override
	public void myAction() throws Exception {
		getElement().clear();
		MessageTemplate mt = MessageTemplate.MatchPerformative(ACLMessage.REQUEST);
		ACLMessage msg = myAgent.receive(mt);
		if (msg!=null){
			String ticket = ((IstarJadeAgent)myAgent).getNextTicket();
			((IstarJadeAgent)myAgent).getWorkingMessages().put(ticket,msg);
			((AbstractMainGoal)getElement()).setExecutionNumber(ticket);
			log("Agent name="+ myAgent.getName() +": executing. Ticket="+ getElement().getExecutionNumber());
			((AbstractMainGoal)getElement()).deliberate();
			String content = msg.getContent();
			
			getElement().getContent().add(content);
			((IstarJadeAgent)myAgent).setKnowledgeElement(getElement().getExecutionNumber(), getElement());
			((IstarJadeAgent)myAgent).setKnowledgeObject(getElement().getExecutionNumber(), "Message-Received", msg);
			log("Agent name="+ myAgent.getName() +" received a REQUEST for:" + content);
		}
		
	}

	@Override
	public int myOnEnd() {
		if (((AbstractMainGoal)getElement()).deliberateCondition()){
			((AbstractMainGoal)getElement()).undeliberate();
			return 1;
		}
		else{
			return 0;
		}
	}

	@Override
	public boolean done() {
		return true;
	}

	
	
}
